import { observable, runInAction, action, when } from 'mobx';
import Store from './';
import { post } from '../api';

export default class User {
  root: Store;

  constructor(root: Store) {
    this.root = root;
  }

  @observable isLogin: boolean = false; // 登陆状态监听
  @action onLogin = (bind: boolean | (() => void)) => {
    // 登录
    if (typeof bind === 'boolean') {
      this.isLogin = bind;
    } else {
      when(() => this.isLogin, bind);
    }
  };

  isSendCaptcha = false; // 是否已发送验证码
  @observable sendCaptchaTime = 0; // 验证码发送间隔时间

  // 验证码发送
  sendCaptcha = async (data: any) => {
    const { userPhone, ...datas } = data;
    const res = await post(`/chedui/loan/user/sendSms/${userPhone}`, datas, {
      label: '发送验证码',
      noToken: true,
    });
    if (res.code !== 2000) return false;
    this.isSendCaptcha = true;
    runInAction(() => {
      this.sendCaptchaTime = 60;
    });
    const countDown = setInterval(
      action(() => {
        if (this.sendCaptchaTime > 0) {
          this.sendCaptchaTime--;
        } else {
          clearInterval(countDown);
        }
      }),
      1000
    );
  };
}
